<!DOCTYPE html>
<html lang="en">
	<head>
	    <meta charset="UTF-8">
	    <title>websocket demo</title>
	    <script src="jquery-1.11.3.js"></script>
	    
		<script type="text/javascript">

				var urlRoad = 'ws://127.0.0.1:8990/ws;' ;

				var ws = null;			

				function connect () {

					if(ws != null) return;
					
		            ws = new WebSocket(urlRoad + $("#fname").val());

					ws.onopen = WSonOpen;
					ws.onmessage = WSonMessage;
					ws.onclose = WSonClose;
					ws.onerror = WSonError;

				}

				function WSonClose() {
		       		ws = null;
		           console.log("连接关闭。");

		       };
		 
		       function WSonError() {
		       		ws = null;
		           console.log("WebSocket错误。");
		       };

		       function send() {
			       	if(ws == null) {
			       		alert("未登录");
			       		return;
			       	}

		       		var text = $("#tosend").val();
		       		if(text.trim() == '') return;
		       		$("#tosend").val('');
		       		ws.send(text);
		       }

		       	var lastTime = new Date().valueOf();
				function WSonOpen() {
		           
		       		setInterval(function(){
		       			console.log('send - ' + new Date().valueOf());
			            ws.send("HeartBeat");

			        }, 4000);

		           setTimeout(function(){
			            setInterval(function(){
			            	var now = new Date().valueOf();
			            	console.log('chek - ' + now);
				        	if((now - lastTime) > 8000) {
				        		console.log(now - lastTime);
				        		console.log('与服务器断开连接了');
				        		ws.close();
				        		connect();
				        	}
				        }, 4000);
			        }, 1000);
		       };
		 		
		       function WSonMessage(event) {   

		           lastTime = new Date().valueOf();
		           console.log('get  - ' + lastTime);

			        if(event.data == 'HeartBeat') 
		           		$("#heart").val("=" + $("#heart").val());   
		           	else if(-1 != event.data.indexOf("[在线用户]"))
		           		$("#online").val(event.data);   
		           	else 
		           		$("#board").val(event.data + "\n" + $("#board").val());  

		       };
	
		</script>
	</head>
	<body>
		用户名: <input type="text" id="fname"><input type="submit" onclick="connect()" value="登陆">
		<br><textarea onchange="this.scrollTop=this.scrollHeight" style= "overflow-x:auto" id="board" rows=10 cols=80></textarea>
		<br><input id="tosend" type="text" style="width:400px"></input><input type="submit" onclick="send()" value="发送">
		<br><textarea onchange="this.scrollTop=this.scrollHeight" style= "overflow-x:auto" id="heart" rows=10 cols=80></textarea>
		<br><textarea onchange="this.scrollTop=this.scrollHeight" style= "overflow-x:auto" id="online" rows=10 cols=80></textarea>

	</body>
</html>
